package com.nlscan.ncomgateway.core.common

import android.app.Application
import com.nlscan.ble.NlsBleManager
import com.nlscan.ble.NlsReportHelper
import com.nlscan.ble.common.NlsBleConfig
import com.nlscan.ble.common.SdkConfig
import com.nlscan.ble.util.NLogUtil
import com.nlscan.qdkit.common.core.app.App
import com.nlscan.ncomgateway.core.data.repository.DeviceRepository
import com.nlscan.ncomgateway.core.database.AppDatabase
import com.nlscan.ncomgateway.core.database.dao.DeviceDao
import com.nlscan.ncomgateway.core.manager.ProfileManager
import com.nlscan.ncomgateway.core.remote.DeviceRemoteDataSource
import com.nlscan.ncomgateway.core.sdk.udp.UdpManager

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/7/12
 *  desc  :
 * </pre>
 */
abstract class CoreApp : App(){

    lateinit var deviceDao: DeviceDao
    //    @Inject
    public lateinit var deviceRepository: DeviceRepository

    override fun onCreate() {
        super.onCreate()
        NLogUtil.i("CoreApp onCreate")


        deviceDao = AppDatabase.get(this).deviceDao()
        // TODO: 需要迁移到底层来初始化 ？
//        VmHelper.init(this)
        initSdk()
        val deviceRemote = DeviceRemoteDataSource(NlsBleManager.getInstance())
        deviceRepository = DeviceRepository(deviceDao, deviceRemote)

    }

    fun initSdk() {
        //[bug] startForegroundService() not allowed due to mAllowStartForeground false
        try {
            initNlsBleSdk()
        }catch (e:Exception) {
            NLogUtil.e("initNlsBleSdk e: " + e.message)
        }

        UdpManager.init(this)
        ProfileManager.init(this)
    }

    // TODO: 是否下沉到core层
    fun initNlsBleSdk() {
        //temp
        SdkConfig.needCreateAliveService = true

        //init log context
        NlsReportHelper.getInstance().init(this)
        //default open save log to sdcard
        NlsReportHelper.getInstance().isSaveLogEnable = true
        val config = NlsBleConfig.Builder()
            .setSupportMultiConnect(true)
            .build()

        //获取db中的设备列表
        val list = getDeviceAddressListFromDb(deviceDao) ?: arrayListOf()
        NlsBleManager.getInstance().init(this, config, list)
    }

    fun getDeviceAddressListFromDb(deviceDao: DeviceDao): List<String>? {
        //疑问，这里拿到的 list 等于 null，是因为没有人观察，所以拿不到值么，验证是的
        //val list = deviceDao.getDeviceEntities().value
        //[疑问]，db若为空，返回 size= 0 还是 null？
        val list = deviceDao.getDeviceEntityList()
        NLogUtil.i("list size： " + list.size)
        return list.map {
            it.address
        }
    }

    companion object {

        fun getContext(): Application {
            return getInstance()
        }

        fun getInstance(): CoreApp {
            return (App.getInstance() as? CoreApp)!!
        }
    }
}